//------------------------------------------------------------------------------
// <copyright file="WatermarkTextBox.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Diagnostics;
using System.Windows.Data;
using System.Windows.Input;

namespace DotBeer.UI.WPFClient
{
    public class WatermarkTextBox : TextBox
    {
        #region properties

        public static readonly DependencyProperty WatermarkTextProperty =
            DependencyProperty.Register("WatermarkText",
                                        typeof(string),
                                        typeof(WatermarkTextBox),
                                        new PropertyMetadata(WatermarkText_Changed));

        public string WatermarkText
        {
            get { return (string)this.GetValue(WatermarkTextProperty); }
            set { this.SetValue(WatermarkTextProperty, value); }
        }

        #endregion

        #region constructors

        public WatermarkTextBox()
        {
            this.GotFocus += new RoutedEventHandler(WatermarkTextBox_GotFocus);
            this.LostFocus += new RoutedEventHandler(WatermarkTextBox_LostFocus);

        }

        #endregion

        #region private methods

        void WatermarkTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            this.SetWatermarkText();
            Validation.ClearInvalid(this.GetBindingExpression(TextBox.TextProperty));
        }

        void WatermarkTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            this.Text = "dupa"; //First set some text, then clear text. This is need to avoid some kind of bug.
            this.Text = "";     //If control gets second time focus and sets Text to "", Text won't change.
            this.FontStyle = FontStyles.Normal;
        }

        private void SetWatermarkText()
        {
            this.Text = this.WatermarkText;
            this.FontStyle = FontStyles.Italic;
        }

        private static void WatermarkText_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            WatermarkTextBox watermark = d as WatermarkTextBox;
            watermark.SetWatermarkText();
        }

        #endregion
    }
}
